import datetime
import os
import string

from django.shortcuts import get_object_or_404
from django.conf import settings
import random

from User.models import MyUser as User
from django.http import HttpResponse, JsonResponse, HttpResponseRedirect

from django.http import HttpResponse, JsonResponse, HttpResponseNotFound, HttpResponseBadRequest

from django.shortcuts import render
from Payment.models import Payment
from Shop.models import Order, OrderShip, Commodity
import json

from alipay import AliPay


def get_alipay(request):
    si_path = os.path.join(settings.MEDIA_ROOT, 'key/应用私钥RSA2048.txt')
    go_path = os.path.join(settings.MEDIA_ROOT, 'key/支付宝公钥.txt')
    app_private_key_string = open(si_path).read()
    alipay_public_key_string = open(go_path).read()

    alipay = AliPay(
        appid="9021000133687326",
        app_notify_url=None,  # 默认回调 url
        app_private_key_string=app_private_key_string,
        # 支付宝的公钥，验证支付宝回传消息使用，
        alipay_public_key_string=alipay_public_key_string,
        sign_type="RSA2",  # RSA 或者 RSA2
        debug=True,  # 默认 False，设置True开沙盒模式
    )
    data = json.loads(request.body.decode('utf-8'))
    commodity_list = data.get('commodity_list')
    subtotal = data.get('subtotal')
    print(len(commodity_list))
    print(type(commodity_list))
    if type(commodity_list) == list:
        show_name = commodity_list[0]['name'] + "等商品" if len(commodity_list) > 1 else commodity_list[0]['name']
    else:
        show_name = commodity_list['name']
    # 利用时间戳随机生成支付号
    out_trade_no = "".join(random.sample(string.ascii_letters + string.digits, 32))
    res = alipay.api_alipay_trade_page_pay(
        out_trade_no=out_trade_no,
        total_amount=float(subtotal),  # 价格(接收数据)
        subject=show_name,  # 名称(接收数据)
        return_url='http://82.156.146.198:9090/#/',  # 支付成功后会跳转的页面
        # notify_url='http://127.0.0.1:8000',  # 回调地址，支付成功后支付宝会向这个地址发送post请求
    )

    GATEWAY = 'https://openapi-sandbox.dl.alipaydev.com/gateway.do?'
    # 支付链接
    pay_url = GATEWAY + res
    return JsonResponse({'pay_url': pay_url})


# 增加支付记录并关联订单

def create_payment_with_order(request):
    if request.method == 'POST':
        data = json.loads(request.body.decode('utf-8'))
        commodity_list = data.get('commodity_list')
        order_list = data.get('order_list')
        user_id = data.get('user_id')
        print(order_list)
        print(commodity_list)
        i = 0
        if type(commodity_list) != list:
            payment = Payment()
            payment.amount = 1
            payment.status = '已完成'
            payment.payment_method = '支付宝'
            payment.timestamp = datetime.datetime.now()
            payment.order_id = order_list['id']
            payment.user_id = user_id
            payment.save()
            order = Order.objects.get(user_id=user_id, id=order_list['id'])
            order.status_buyer = '已付款'
            order.save()
        else:
            for item in commodity_list:
                payment = Payment()
                payment.amount = item['quantity']
                payment.status = '已完成'
                payment.payment_method = '支付宝'
                payment.timestamp = datetime.datetime.now()
                payment.order_id = order_list[i]
                payment.user_id = user_id
                payment.save()
                order = Order.objects.get(user_id=user_id, id=order_list[i])
                order.status_buyer = '已付款'
                order.save()
                i = i + 1

        # order_id = data.get('order_num')
        # amount = data.get('amount')
        # payment_method = data.get('pay_type')
        #
        # order = get_object_or_404(Order, id=order_id)
        #
        # payment_status = 'completed'  # 假设支付状态逻辑在这里。
        #
        # payment = Payment.objects.create(
        #     order=order,
        #     amount=amount,
        #     payment_method=payment_method,
        #     status=payment_status,
        #     timestamp=datetime.datetime.now(),
        #     user=request.user
        # )
        #
        # if payment_status == 'completed':
        #     order.status_buyer = '已支付'
        #     order.status_merchant = '待发货'
        #     order.save()
        #
        return JsonResponse({'status': 'success'})
    else:
        return HttpResponseBadRequest('无效的请求方法')


# 删除支付记录并解除与订单的关联
def delete_payment_and_detach_order(request, payment_id):
    if request.method == 'DELETE':
        payment = get_object_or_404(Payment, id=payment_id)

        # 获取关联的订单
        order = payment.order

        # 假设这里有一些需要处理的订单状态逻辑
        order.status_buyer = '待支付'
        order.status_merchant = '待处理'
        order.save()

        payment.delete()
        return JsonResponse({'status': 'success'})
    else:
        return HttpResponseBadRequest('无效的请求方法')


# 修改支付记录关联的订单
def update_payment_order(request, payment_id):
    if request.method == 'PUT':
        payment = get_object_or_404(Payment, id=payment_id)
        data = json.loads(request.body.decode('utf-8'))

        new_order_id = data.get('new_order_id')
        new_order = get_object_or_404(Order, id=new_order_id)

        # 将支付记录关联到新的订单
        payment.order = new_order
        payment.save()

        return JsonResponse({'status': 'success'})
    else:
        return HttpResponseBadRequest('无效的请求方法')


def get_order_id_from_payment(request, payment_id):
    if request.method == 'GET':
        payment = get_object_or_404(Payment, id=payment_id)

        # 获取关联的订单ID
        order_id = payment.order_id

        return JsonResponse({'order_id': order_id})
    else:
        return HttpResponseBadRequest('无效的请求方法')


# 获取支付记录的时间戳
def get_payment_timestamp(request, payment_id):
    if request.method == 'GET':
        payment = get_object_or_404(Payment, id=payment_id)

        # 获取时间戳字段的值
        timestamp = payment.timestamp

        # 将时间戳转换为字符串形式，以便在 JSON 中返回
        timestamp_str = str(timestamp)

        return JsonResponse({'timestamp': timestamp_str})
    else:
        return HttpResponseBadRequest('无效的请求方法')


# 更新支付记录的时间戳为当前时间
def update_payment_timestamp(request, payment_id):
    if request.method == 'PUT':
        payment = get_object_or_404(Payment, id=payment_id)

        # 将时间戳字段设置为当前时间
        payment.timestamp = datetime.datetime.now()
        payment.save()

        return JsonResponse({'status': 'success'})
    else:
        return HttpResponseBadRequest('无效的请求方法')


# 获取支付记录的支付方法
def get_payment_method(request, payment_id):
    if request.method == 'GET':
        payment = get_object_or_404(Payment, id=payment_id)

        # 获取支付方法字段的值
        payment_method = payment.payment_method

        return JsonResponse({'payment_method': payment_method})
    else:
        return HttpResponseBadRequest('无效的请求方法')


# 修改支付记录的支付方法
def update_payment_method(request, payment_id):
    if request.method == 'PUT':
        payment = get_object_or_404(Payment, id=payment_id)
        data = json.loads(request.body.decode('utf-8'))

        # 获取新的支付方法值
        new_payment_method = data.get('new_payment_method')

        # 更新支付方法字段的值
        payment.payment_method = new_payment_method
        payment.save()

        return JsonResponse({'status': 'success'})
    else:
        return HttpResponseBadRequest('无效的请求方法')


# 获取支付记录的状态
def get_payment_status(request, payment_id):
    if request.method == 'GET':
        payment = get_object_or_404(Payment, id=payment_id)

        # 获取状态字段的值
        payment_status = payment.status

        return JsonResponse({'payment_status': payment_status})
    else:
        return HttpResponseBadRequest('无效的请求方法')


# 修改支付记录的状态
def update_payment_status(request, payment_id):
    if request.method == 'PUT':
        payment = get_object_or_404(Payment, id=payment_id)
        data = json.loads(request.body.decode('utf-8'))

        # 获取新的状态值
        new_payment_status = data.get('new_payment_status')

        # 更新状态字段的值
        payment.status = new_payment_status
        payment.save()

        return JsonResponse({'status': 'success'})
    else:
        return HttpResponseBadRequest('无效的请求方法')


# 获取某个用户的支付记录
def get_payment_records(request):
    data = json.loads(request.body.decode('utf-8'))
    if data is None:
        return HttpResponseBadRequest('无效的请求方法')
    user_id = data.get('user_id')
    start = data.get('start')
    limit = data.get('limit')
    print(user_id, start, limit)
    # 查找该用户的所有支付记录
    payments = Payment.objects.filter(user_id=user_id, status='已完成')[int(start):int(start) + int(limit)].values()
    print(payments)
    # 根据order_id反向查找订单，获取订单的商品数量和商品单价
    for payment in payments:
        ordership = OrderShip.objects.get(order__id=payment['order_id'])
        payment['quantity'] = ordership.quantity
        payment['name'] = ordership.commodity.name
    print(payments)
    return JsonResponse({'items': list(payments)})
